﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using Things.Common;
using com.yeepay.icc;

namespace Things.ThingsWeb
{
    public class PageUtility : System.Web.UI.Page
    {
        protected Things.Model.Buyer CurrentBuyer
        {
            get
            {
                Things.Model.Buyer buyer = null;
                if (Session[ConstantString.SessionCurrentBuyerAccount] == null)
                {
                    buyer = null;
                }
                else
                {
                    buyer = Session[ConstantString.SessionCurrentBuyerAccount] as Things.Model.Buyer;
                }
                return buyer;
            }
        }

        public string UploadFile(FileUpload FileUpload1)
        {
            string imageURL = string.Empty;
            try
            {
                string filePath = FileUpload1.PostedFile.FileName;
                string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                string folderName = CreateFolder();
                string serverPath = Server.MapPath("~/images/" + folderName + "/") + fileName;
                FileUpload1.PostedFile.SaveAs(serverPath);

                imageURL = "/images/" + folderName + "/" + fileName;
            }
            catch
            {
                imageURL = string.Empty;
            }

            return imageURL;
        }

        public string CreateFolder()
        {
            DateTime   dt=System.DateTime.Now;
            string dirName = HttpContext.Current.Server.MapPath("~/images/") + dt.ToString("yyyyMMdd");
            string folderName = dt.ToString("yyyyMMdd");
            try 
            { 
                  if(System.IO.Directory.Exists(dirName) )
                  { 
                        // throw   new   Exception( "目录已存在 ");                       
                  } 
                  System.IO.Directory.CreateDirectory(dirName); 

            } 
            catch
            {
                folderName = string.Empty;
            }
            return folderName;
        }

       
        /***** 购物车 session *****/
        public void Add(Guid GoodsPriceID, int count)
        {
            if (GoodsPriceID.Equals(Guid.Empty))
            {
                return;
            }

            List<Things.Model.GoodsCart> goodsCart = Session[ConstantString.SessionGoodsCart] as List<Things.Model.GoodsCart>;

            if (goodsCart == null)
            {
                goodsCart = new List<Model.GoodsCart>();
                Things.Model.GoodsCart good = new Things.Model.GoodsCart { GoodsPriceID = GoodsPriceID, GoodsCount = count };
                goodsCart.Add(good);
            }
            else
            {
                Things.Model.GoodsCart good = IsExisted(GoodsPriceID, goodsCart);
                if (good == null)
                {
                    good = new Things.Model.GoodsCart { GoodsPriceID = GoodsPriceID, GoodsCount = count };
                    goodsCart.Add(good);
                }
                else
                {
                    good.GoodsCount = count;
                }                
            }

            Session[ConstantString.SessionGoodsCart] = goodsCart;
        }

        public void Delete(Guid GoodsPriceID)
        {
            if (GoodsPriceID.Equals(Guid.Empty))
            {
                return;
            }

            List<Things.Model.GoodsCart> goodsCart = Session[ConstantString.SessionGoodsCart] as List<Things.Model.GoodsCart>;

            if (goodsCart == null)
            {
                return;
            }
            else
            {
                Things.Model.GoodsCart good = IsExisted(GoodsPriceID, goodsCart);
                if (good != null)
                {
                    goodsCart.Remove(good);
                }
            }

            Session[ConstantString.SessionGoodsCart] = goodsCart;
        }

        private Things.Model.GoodsCart IsExisted(Guid GoodsPriceID, List<Things.Model.GoodsCart> goodsCart)
        {
            Things.Model.GoodsCart flag = null;

            foreach (var temp in goodsCart)
            {
                if (temp.GoodsPriceID == GoodsPriceID)
                {
                    flag = temp;
                    break;
                }
            }

            return flag;
        }

        /***** 购物车 *****/

        protected Things.Model.Buyer GetCurrentBuyer()
        {
            Things.Model.Buyer buyer=null;
            if (Session[ConstantString.SessionCurrentBuyerAccount] == null)
            {
                buyer = null;
            }
            else
            {
                buyer = Session[ConstantString.SessionCurrentBuyerAccount] as Things.Model.Buyer;
            }
            return buyer;
        }

        public static string GetLimitedString(string sourceStr, int limitLength=11)
        {
            string temp = string.Empty;

            if (string.IsNullOrEmpty(sourceStr) == false)
            {
                if (limitLength <= 0)
                {
                    temp = sourceStr;
                }
                else
                {
                    if (sourceStr.Length > limitLength)
                    {
                        temp = sourceStr.Remove(limitLength);
                    }
                    else
                    {
                        temp = sourceStr;
                    }
                }
            }

            return temp;
        }

        public static string GetLimitedStringWithDotted(string sourceStr, int limitLength = 11)
        {
            string temp = string.Empty;

            if (string.IsNullOrEmpty(sourceStr) == false)
            {
                if (limitLength <= 0)
                {
                    temp = sourceStr;
                }
                else
                {
                    if (sourceStr.Length > limitLength)
                    {
                        temp = sourceStr.Remove(limitLength);
                        temp = temp + "...";
                    }
                    else
                    {
                        temp = sourceStr;
                    }
                }
            }

            return temp;
        }

        /***** 购物车 cookie *****/       
        public  void AddToGoodsCart(HttpContext context,  Guid goodsPriceID, int count, string cartPageUrl)
        {
            //往购物车中添加商品
            HttpCookie hc = null;
            if (context.Request.Cookies[Things.Common.ConstantString.CookieGoodsCart] == null)
            {
                //如果Cookies中不存在ShoppingCart，则创建
                hc = new HttpCookie(Things.Common.ConstantString.CookieGoodsCart);
            }
            else
            {
                //如果Cookies中存在ShoppingCart，则取出
                hc = context.Request.Cookies[Things.Common.ConstantString.CookieGoodsCart];
            }

            //标记在购物车中是否存在本次选择的物品
            bool isExist = false;

            //在购物车的Cookies中查找是否存在这次要选择的物品
            foreach (string item in hc.Values.Keys)
            {
                if (item == goodsPriceID.ToString("N"))
                {
                    isExist = true;
                    break;
                }
            }
            if (!isExist)
            {
                //如果选择的内容在购物车中没有，则创建一个新的子键
                hc.Values.Add(goodsPriceID.ToString("N"), count.ToString());
            }
            else
            {
                //如果选择的内容在购物车中没，则删除原来的，添加一个新的
                //int num = int.Parse(hc.Values[id].Split(new char[] { '|' })[3]) + 1;
                hc.Values.Remove(goodsPriceID.ToString("N"));
                hc.Values.Add(goodsPriceID.ToString("N"), count.ToString());
            }
            hc.Expires = DateTime.Now.AddDays(1);
            context.Response.Cookies.Add(hc);
            context.Response.Redirect(cartPageUrl);
        }

        public  List<Things.Model.GoodsCart> GetGoodsCart(HttpContext context)
        {
            HttpCookie hc = null;
            if (context.Request.Cookies[Things.Common.ConstantString.CookieGoodsCart] == null)
            {
                return null;
            }
            else
            {
                hc = context.Request.Cookies[Things.Common.ConstantString.CookieGoodsCart];
            }

            List<Things.Model.GoodsCart> goodsCart = new List<Model.GoodsCart>();

            for (int index = 0; index < hc.Values.Count; index++)
            {
                goodsCart.Add(new Model.GoodsCart { GoodsPriceID = new Guid(hc.Values.Keys[index]), GoodsCount = int.Parse(hc.Values[index]) });

                
            }
            return goodsCart;
        }

        public void RemoveFromGoodsCart(HttpContext context, Guid goodsPriceID, string cartPageUrl)
        {
            //往购物车中添加商品
            HttpCookie hc = null;
            if (context.Request.Cookies[Things.Common.ConstantString.CookieGoodsCart] != null)
            {
                hc = context.Request.Cookies[Things.Common.ConstantString.CookieGoodsCart];
            }

            //在购物车的Cookies中查找是否存在这次要选择的物品
            foreach (string item in hc.Values.Keys)
            {
                if (item == goodsPriceID.ToString("N"))
                {
                    hc.Values.Remove(goodsPriceID.ToString("N"));
                    break;
                }
            }
            hc.Expires = DateTime.Now.AddDays(1);
            context.Response.Cookies.Add(hc);
            context.Response.Redirect(cartPageUrl);
        }
        /***** cookie *****/

        //
        // 付款
        protected string p1_MerId = Buy.GetMerId();

        protected string p2_Order;
        protected string p3_Amt;
        protected string p4_Cur;
        protected string p5_Pid;
        protected string p6_Pcat;

        protected string p7_Pdesc;
        protected string p8_Url;
        protected string p9_SAF;
        protected string pa_MP;
        protected string pd_FrpId;

        protected string pr_NeedResponse;
        protected string hmac;

        protected string reqURL_onLine = Buy.GetBuyUrl();

        protected void Pay(string goodsOrderNumber, string totalPrice, string goodsNames, string goodsCategory,
                                string goodsDescription, string returnURL, string goodsExtentInfomation)
        {
            string temp = string.Empty;

             

            //1
            //p2_Order	商户平台订单号
            //若不为""，提交的订单号必须在自身账户交易中唯一;为""时，易宝支付会自动生成随机的商户订单号.
            p2_Order = goodsOrderNumber;
            //p3_Amt	交易金额  精确两位小数，最小值为0.01,为持卡人实际要支付的金额.                 
            p3_Amt = totalPrice;
            //交易币种,固定值"CNY".
            p4_Cur = "CNY";
            //商品名称
            //用于支付时显示在易宝支付网关左侧的订单产品信息.
            p5_Pid = goodsNames;
            //商品种类
            p6_Pcat = goodsCategory;
            //2
            //商品描述
            p7_Pdesc = goodsDescription;
            //商户接收支付成功数据的地址,支付成功后易宝支付会向该地址发送两次成功通知.
            p8_Url = returnURL;
            //送货地址
            //为“1”: 需要用户将送货地址留在易宝支付系统;为“0”: 不需要，默认为 ”0”.
            p9_SAF = "0";
            //商户扩展信息
            //商户可以任意填写1K 的字符串,支付成功时将原样返回.	
            pa_MP = goodsExtentInfomation;
            //银行编码
            //默认为""，到易宝支付网关.若不需显示易宝支付的页面，直接跳转到各银行、神州行支付、骏网一卡通等支付页面，该字段可依照附录:银行列表设置参数值.
            pd_FrpId = "";
            //3
            //应答机制
            //默认为"1": 需要应答机制;
            pr_NeedResponse = "1";

            temp = Buy.CreateBuyHmac(p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse);

            string[] infos = temp.Split(new string[] { ";#" }, StringSplitOptions.None);

            Session[Common.ConstantString.SessionPayForm] = infos[1];
            Response.Redirect("~/GoodsOrders/Pay.aspx");

        }

    }
}